package com.lunhui.search.dal.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lunhui.search.dal.dao.UserDao;
import com.lunhui.search.dal.model.User;
import org.springframework.stereotype.Repository;

import java.io.IOException;

/**
 * @author renminghe-kg
 */

@Repository("userDao")
public class UserDaoImpl extends ESBaseServiceImpl implements UserDao {

    @Override
    public User searchByName(String userName) throws IOException, RuntimeException {

        JSONObject queryParam = new JSONObject();

        String queryStr = "{ \"match\": {\"account\": \"" + userName + "\"} }";
        queryParam.put("query", JSON.parseObject(queryStr));

        JSONObject jsonObject = getEs(queryParam, "/lunhui/user/_search");
        return parseESResponse(jsonObject);
    }

    @Override
    public Integer addUser(User user) throws IOException, RuntimeException {

        String userStr = JSONObject.toJSONString(user);

        addEs(userStr, "/lunhui/user/");
        return 1;
    }

    private User parseESResponse (JSONObject res) {
        User user = null;

        if (res != null) {
            JSONObject hits = (JSONObject) res.get("hits");

            if (hits.get("hits") != null) {
                JSONArray jsonArray = (JSONArray) hits.get("hits");
                Object[] objects = jsonArray.toArray();

                if (objects.length > 0) {
                    for (Object object : objects) {
                        JSONObject item = (JSONObject) object;

                        if (item.get("_source") != null) {
                            JSONObject userStr = (JSONObject) item.get("_source");
                            user = JSONObject.parseObject(userStr.toJSONString(), User.class);
                        }
                    }
                }
            }
        }


        return user;
    }
}